﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using HolcimProject.Function;
using HolcimProject.Common.DTO;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using HolcimProject.Common;
using System.Web;
using SPTraceLogger;
using System.Collections;
using System.Collections.Generic;
namespace HolcimProject.ControlTemplates.HolcimProject
{
    public partial class FindingCreate : UserControl
    {

        int findingID = 0;
       
        #region Property

        public bool Flat
        {
            get
            {
                try
                {
                    return Convert.ToBoolean(HttpContext.Current.Request.QueryString["flat"]);
                    // return 6;
                }
                catch
                {
                    return false;
                }
            }
        }

        public int FindingID
        {
            get
            {
                try
                {
                    return findingID;
                    //return Convert.ToInt32(Request.QueryString["findingid"]);
                    //return 10;
                }
                catch
                {
                    return 0;
                }
            }
        }

        public int FindingTaskID
        {
            get
            {
                try
                {
                    return Convert.ToInt32(Request.QueryString["findingtaskid"]);
                    //return 6;
                }
                catch
                {
                    return 0;
                }
            }
        }

        #endregion

        #region Event

        private FunctionFinding functionFinding;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                functionFinding = new FunctionFinding();
                if (FindingTaskID != 0)
                {
                    GetParameter();
                    SetStatusUpdateOrNew();
                    LoadInformationProcess();
                }
                else
                {
                    SetStatusUpdateOrNew();
                }
                if (!Page.IsPostBack)
                {
                    BindDataToDropDown();
                    if (FindingID != 0)
                    {
                        LoadFinding();
                    }
                }
            }
            catch (Exception ex)
            {
                SPLoggingService.WriteULSError("Finding", Categories.WebPart, ex);
            }
        }

        protected void drSite_SelectedIndexChanged(object sender, EventArgs e)
        {
            drDepartment.Items.Clear();
            drAuditeeDepartment.Items.Clear();

            // dropdown  department
            string siteName = drSite.SelectedItem.Text;
            drDepartment.DataTextField = "Title";
            drDepartment.DataValueField = "ID";
            drDepartment.DataSource = functionFinding.GetAllDeparment(siteName);
            drDepartment.DataBind();
            //end

            // dropdown audit department
            string departmentName = drDepartment.SelectedItem.Text;
            drAuditeeDepartment.DataTextField = "Title";
            drAuditeeDepartment.DataValueField = "ID";
            drAuditeeDepartment.DataSource = functionFinding.GetAllAuditDepartment(departmentName);
            drAuditeeDepartment.DataBind();
            //end
        }

        protected void drDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {
            drAuditeeDepartment.Items.Clear();
            string departmentName = drDepartment.SelectedItem.Text;
            // dropdown Classification
            drAuditeeDepartment.DataTextField = "Title";
            drAuditeeDepartment.DataValueField = "ID";
            drAuditeeDepartment.DataSource = functionFinding.GetAllAuditDepartment(departmentName);
            drAuditeeDepartment.DataBind();
            //end
        }

        protected void drSystem_SelectedIndexChanged(object sender, EventArgs e)
        {
            drClause.Items.Clear();
            // dropdown Clause
            string system = drSystem.SelectedItem.Text;
            drClause.DataTextField = "Title";
            drClause.DataValueField = "ID";
            drClause.DataSource = functionFinding.GetAllClause(system);
            drClause.DataBind();
            //end
        }

        protected void btnSendAndNew_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidationInput())
                {
                    FindingDTO finding = functionFinding.UpdateFinding(GetFinding(""));
                    if (finding != null)
                    {
                        functionFinding.UpdateTask(GetInfoTaskAuditor(finding.Id));
                        functionFinding.UpdateTask(GetInfoTaskAuditee(finding.Id));
                    }
                    txtFinding.Text = "";
                }
            }
            catch (Exception ex)
            {
                messageError.InnerHtml = "This action cannot be performed successfully. Please contact your system administrator or try again.";
                SPLoggingService.WriteULSError("Finding", Categories.WebPart, ex);
            }
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidationInput())
                {
                    FindingDTO finding = functionFinding.UpdateFinding(GetFinding(""));
                    if (finding != null)
                    {
                        functionFinding.UpdateTask(GetInfoTaskAuditor(finding.Id));
                        functionFinding.UpdateTask(GetInfoTaskAuditee(finding.Id));
                    }
                    closeForm();
                }
            }
            catch (Exception ex)
            {
                messageError.InnerHtml = "This action cannot be performed successfully. Please contact your system administrator or try again.";
                SPLoggingService.WriteULSError("Finding", Categories.WebPart, ex);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidationInput())
                {
                    FindingDTO finding = functionFinding.UpdateFinding(GetFinding("Edit"));
                   // functionFinding.UpdateTask(GetInfoTaskAuditor(finding.Id));
                    closeForm();
                }

            }
            catch (Exception ex)
            {
                messageError.InnerHtml = "This action cannot be performed successfully. Please contact your system administrator or try again.";
                SPLoggingService.WriteULSError("Finding", Categories.WebPart, ex);
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            closeForm();
        }

        #endregion

        #region Function

        /// <summary>
        /// Get parameter
        /// </summary>
        private void GetParameter()
        {
            ParameterDTO parameter = functionFinding.GetParameterByFindTaskID(FindingTaskID);
            if (parameter != null)
            {               
                findingID = parameter.FindingID;
            }
        }

        /// <summary>
        /// close form
        /// </summary>
        private void closeForm()
        {
            HttpContext context = HttpContext.Current;
            if (HttpContext.Current.Request.QueryString["IsDlg"] != null)
            {
                context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup()</script>");
                context.Response.Flush();
                context.Response.End();
            }
            else
            {
                Response.Redirect(Constants.Link_PageAllFinding);
            }
        }


        /// <summary>
        /// Get info task for Auditor
        /// </summary>
        /// <returns></returns>
        private FindingTaskDTO GetInfoTaskAuditor(int findingID)
        {
            FindingTaskDTO findingTask = new FindingTaskDTO();
            findingTask.IdFinding = findingID.ToString();
            SPUser currentUser = Utilities.GetCurrentUser(Constants.Site_Url);
            findingTask.Owner = currentUser.ID + ";#" + currentUser.LoginName;
            findingTask.Role = Constants.Role_Auditor;
            findingTask.State = Constants.State_CreateFinding;
            findingTask.Status = Constants.Status_NoYet;
            findingTask.Flat = "done";
            if (attackFile.FileName != "")
            {
                findingTask.AttackFileName = attackFile.FileName;
                findingTask.AttackFile = attackFile.FileBytes;
            }
            return findingTask;
            
        }

        /// <summary>
        /// Get info task for Auditee
        /// </summary>
        /// <returns></returns>
        private FindingTaskDTO GetInfoTaskAuditee(int findingID)
        {
            FindingTaskDTO findingTask = new FindingTaskDTO();
            findingTask.IdFinding = findingID.ToString();
            string users = "";
            for (int i = 0; i < ppAuditee.ResolvedEntities.Count; i++)
            {
                PickerEntity pickerEntity = (PickerEntity)ppAuditee.ResolvedEntities[i];
                string username = pickerEntity.Key;
                SPUser user = new SPSite(Constants.Site_Url).OpenWeb().EnsureUser(username);
                users += user.ID.ToString() + ";#" + user.LoginName.ToString() + ";#";
            }
            findingTask.Owner = users;
            findingTask.Role = Constants.Role_Auditee;
            findingTask.State = Constants.State_EditActionLog;
            findingTask.Status = Constants.Status_NoYet;
            return findingTask;
        }

        /// <summary>
        /// Get info finding
        /// </summary>
        /// <returns></returns>
        private FindingDTO GetFinding(string status)
        {
            FindingDTO finding = new FindingDTO();
            // form is edit. get finding id
            if (status == "Edit")
            {
                finding.Id = FindingID;
            }
            //end
            finding.AuditName = drAuditName.SelectedItem.Value;
            finding.System = drSystem.SelectedItem.Value;
            finding.Clause = drClause.SelectedItem.Value;
            finding.Site = drSite.SelectedItem.Value;
            finding.Department = drDepartment.SelectedItem.Value;
            finding.AuditeeDepartment = drAuditeeDepartment.SelectedItem.Value;
            finding.Classification = drClassification.SelectedItem.Value;
            string users = "";
            for (int i = 0; i < ppLeadAuditor.ResolvedEntities.Count; i++)
            {
                PickerEntity pickerEntity = (PickerEntity)ppLeadAuditor.ResolvedEntities[i];
                string username = pickerEntity.Key;
                SPUser user = new SPSite(Constants.Site_Url).OpenWeb().EnsureUser(username);
                users += user.ID.ToString() + ";#" + user.LoginName.ToString() + ";#";
            }
            finding.LeadAuditor = users;

            users = "";
            for (int i = 0; i < ppAuditee.ResolvedEntities.Count; i++)
            {
                PickerEntity pickerEntity = (PickerEntity)ppAuditee.ResolvedEntities[i];
                string username = pickerEntity.Key;
                SPUser user = new SPSite(Constants.Site_Url).OpenWeb().EnsureUser(username);
                users += user.ID.ToString() + ";#" + user.LoginName.ToString() + ";#";
            }
            finding.Auditee = users;
            finding.Finding = txtFinding.Text;
            return finding;
        }

        /// <summary>
        /// Binding data to dropdown
        /// </summary>
        private void BindDataToDropDown()
        {
            // dropdown auditname
            drAuditName.DataTextField = "Title";
            drAuditName.DataValueField = "ID";
            drAuditName.DataSource = functionFinding.GetAllAuditName();
            drAuditName.DataBind();
            //end

            // dropdown system
            drSystem.DataTextField = "Title";
            drSystem.DataValueField = "ID";
            drSystem.DataSource = functionFinding.GetAllSystem();
            drSystem.DataBind();
            //end

            // dropdown Clause
            string system = drSystem.SelectedItem.Text;
            drClause.DataTextField = "Title";
            drClause.DataValueField = "ID";
            drClause.DataSource = functionFinding.GetAllClause(system);
            drClause.DataBind();
            //end

            // dropdown Site
            drSite.DataTextField = "Title";
            drSite.DataValueField = "ID";
            drSite.DataSource = functionFinding.GetAllSite();
            drSite.DataBind();
            //end

            // dropdown Classification
            drClassification.DataTextField = "Title";
            drClassification.DataValueField = "ID";
            drClassification.DataSource = functionFinding.GetAllClassification();
            drClassification.DataBind();
            //end

            // dropdown Department
            string siteName = drSite.SelectedItem.Text;
            drDepartment.DataTextField = "Title";
            drDepartment.DataValueField = "ID";
            drDepartment.DataSource = functionFinding.GetAllDeparment(siteName);
            drDepartment.DataBind();
            //end

            // dropdown audit department
            string departmentName = drDepartment.SelectedItem.Text;
            drAuditeeDepartment.DataTextField = "Title";
            drAuditeeDepartment.DataValueField = "ID";
            drAuditeeDepartment.DataSource = functionFinding.GetAllAuditDepartment(departmentName);
            drAuditeeDepartment.DataBind();
            //end
        }

        /// <summary>
        /// Load info finding
        /// </summary>
        private void LoadFinding()
        {
            FindingDTO findingLoad = new FindingDTO();
            findingLoad = functionFinding.GetFindingByID(FindingID, Constants.State_EditActionLog);            
            if (findingLoad != null)
            {
                if (findingLoad.AuditName != "")
                {
                    drAuditName.SelectedValue = findingLoad.AuditName.Split(';')[0];
                }
                if (findingLoad.System != "")
                {
                    drSystem.SelectedValue = findingLoad.System.Split(';')[0];
                }
                if (findingLoad.Clause != "")
                {
                    drClause.SelectedValue = findingLoad.Clause.Split(';')[0];
                }
                if (findingLoad.Site != "")
                {
                    drSite.SelectedValue = findingLoad.Site.Split(';')[0];
                }
                if (findingLoad.Department != "")
                {
                    drDepartment.SelectedValue = findingLoad.Department.Split(';')[0];
                }
                if (findingLoad.AuditeeDepartment != "")
                {
                    drAuditeeDepartment.SelectedValue = findingLoad.AuditeeDepartment.Split(';')[0];
                }
                if (findingLoad.Classification != "")
                {
                    drClassification.SelectedValue = findingLoad.Classification.Split(';')[0];
                }
                if (findingLoad.LeadAuditor != "")
                {
                    ArrayList _arrayList = new ArrayList();
                    string user = findingLoad.LeadAuditor.Split('#')[1];
                    PickerEntity _pickerEntity = new PickerEntity();
                    _pickerEntity.Key = user;
                    _pickerEntity.IsResolved = true;
                    _arrayList.Add(_pickerEntity);
                    ppLeadAuditor.UpdateEntities(_arrayList);
                }
                if (findingLoad.Auditee != "")
                {
                    ArrayList _arrayList = new ArrayList();
                    string user = findingLoad.Auditee.Split('#')[1];
                    PickerEntity _pickerEntity = new PickerEntity();
                    _pickerEntity.Key = user;
                    _pickerEntity.IsResolved = true;
                    _arrayList.Add(_pickerEntity);
                    ppAuditee.UpdateEntities(_arrayList);
                }
                if (findingLoad.Finding != "")
                {
                    txtFinding.Text = findingLoad.Finding;
                }
                
            }
        }

        /// <summary>
        /// Load all tasks of finding
        /// </summary>
        private void LoadInformationProcess()
        {
            try
            {
                if (FindingID != 0)
                {
                    List<FindingTaskDTO> lst = new List<FindingTaskDTO>();
                    lst = functionFinding.GetAllTaskOfFindingByID(FindingID);
                    string html = "";
                    html += @"<div style='font-weight: bold; color: Blue'>
                                Information Processing
                            </div>";
                    html += "<div>";
                    if (lst != null)
                    {
                        html += "<table class='tableInformationProcessing'>";
                        html += "<tr class='ms-viewheadertr ms-vhltr headerinformationprocess'>";

                        html += "<td class='ms-vh' style='width:3%'>";
                        html += "</td >";

                        html += "<td class='ms-vh' style='width:12%'>Date";
                        html += "</td >";

                        html += "<td class='ms-vh' style='width:12%'>Name";
                        html += "</td >";

                        html += "<td class='ms-vh' style='width:12%'>Role";
                        html += "</td >";

                        html += "<td class='ms-vh' style='width:12%'>State";
                        html += "</td >";

                        html += "<td class='ms-vh' style='width:12%'>Status";
                        html += "</td >";

                        html += "<td class='ms-vh' style='width:37%'>Comment";
                        html += "</td >";
                        html += "</tr>";
                        foreach (FindingTaskDTO findingTask in lst)
                        {
                            html += "<tr class='ms-alternating ms-itmhover rowInformationProcessing'>";

                            html += "<td class='ms-vb2' style='width:3%'>";
                            if (findingTask.AttackFileUrl != "")
                            {
                                html += "<a href='" + findingTask.AttackFileUrl + "'>";
                                html += "<img border='0' class='ms-vb-lvitemimg' title='Attachment' alt='Attachment' src='/_layouts/images/attach.gif'>";
                                html += "</a>";
                            }
                            html += "</td >";

                            html += "<td class='ms-vb2' style='width:12%'>";
                            html += "<div class='ms-rtestate-field'>";
                            html += findingTask.DateLastModify.ToString("MM/dd/yyyy");
                            html += "</div>";
                            html += "</td >";

                            html += "<td class='ms-vb2' style='width:12%'>";
                            html += "<div class='ms-rtestate-field'>";
                            try
                            {
                                html += findingTask.Owner == "" ? "" : findingTask.Owner.Split('\\')[1];
                            }
                            catch
                            {
                            }
                            html += "</div>";
                            html += "</td >";

                            html += "<td class='ms-vb2' style='width:12%'>";
                            html += "<div class='ms-rtestate-field'>";
                            html += findingTask.Role;
                            html += "</div>";
                            html += "</td >";

                            html += "<td class='ms-vb2' style='width:12%'>";
                            html += "<div class='ms-rtestate-field'>";
                            html += findingTask.State;
                            html += "</div>";
                            html += "</td >";

                            html += "<td class='ms-vb2' style='width:12%'>";
                            html += "<div class='ms-rtestate-field'>";
                            html += findingTask.Status;
                            html += "</div>";
                            html += "</td >";

                            html += "<td class='ms-vb2' style='width:37%'>";
                            html += "<div class='ms-rtestate-field'>";
                            html += findingTask.Comment;
                            html += "</div>";
                            html += "</td >";
                            html += "</tr>";


                        }
                        html += "</table>";
                    }
                    html += "</div>";
                    InformationProcess.InnerHtml = html;
                }
            }
            catch
            {
            }

        }

        /// <summary>
        /// Check current user had IOSAdmin or Lead auditor
        /// </summary>
        /// <returns></returns>
        public bool CheckCurrentUserHadILOrAuditor()
        {
            bool isIL = false;
            if (FindingID != 0)
            {
                // get current user
                SPUser currentUser = Utilities.GetCurrentUser(Constants.Site_Url);

                // Check user had lead auditor       
                FindingDTO findingLoad = new FindingDTO();
                findingLoad = functionFinding.GetFindingByID(FindingID, Constants.State_EditActionLog);
                if (findingLoad != null)
                {
                    if (currentUser.LoginName.ToUpper() == findingLoad.LeadAuditor.Split('#')[1].ToUpper())
                    {
                        isIL = true;
                    }

                    if (currentUser.LoginName.ToUpper() == findingLoad.Auditor.Split('#')[1].ToUpper())
                    {
                        isIL = true;
                    }
                }
                //end
                // check User had ISO admin
                bool flat = Utilities.CheckUserExitsInGroup(Constants.Site_Url, Constants.Group_ISOAdmin, currentUser.LoginName);
                if (flat == true)
                {
                    isIL = true;
                }
                //end
            }
            return isIL;
        }

        /// <summary>
        /// Check form edit or new
        /// </summary>
        public void SetStatusUpdateOrNew()
        {
            if (CheckCurrentUserHadILOrAuditor() == true && Flat == true)
            {
                btnSave.Visible = true;
                btnSend.Visible = false;
                btnSendAndNew.Visible = false;
            }
            else
            {
                btnSave.Visible = false;
                btnSend.Visible = true;
                btnSendAndNew.Visible = true;
            }
        }

        /// <summary>
        /// validation form
        /// </summary>
        /// <returns></returns>
        private bool ValidationInput()
        {
            messageError.InnerHtml = "";
            int checkValidate = 0;
            if (ppAuditee.ResolvedEntities.Count == 0)
            {
                checkValidate++;
                messageError.InnerHtml = "Please input all fields require";
                return false;
            }
            if (ppLeadAuditor.ResolvedEntities.Count == 0)
            {
                checkValidate++;
                messageError.InnerHtml = "Please input all fields require";
                return false;
            }
            if (txtFinding.Text.Trim() == "")
            {
                checkValidate++;
                messageError.InnerHtml = "Please input all fields require";
                return false;
            }

            if (!ValidationAttachFile())
            {
                checkValidate++;               
                return false;
            }

            if (checkValidate == 0)
            {
                messageError.InnerHtml = "";
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Validation select file
        /// </summary>
        /// <returns></returns>
        private bool ValidationAttachFile()
        {
            if (attackFile.FileName != "")
            {
                if(!CheckFileType(System.IO.Path.GetExtension(attackFile.FileName)))
                {
                    messageError.InnerHtml = "Not support this file type attach.";
                    return false;
                }
                if (attackFile.FileContent.Length > Constants.File_Attach_FileSize)
                {
                    messageError.InnerHtml = "Maximum size of uploaded file should be less than 50 MB.";
                    return false;
                }

                if (attackFile.FileContent.Length == 0)
                {
                    messageError.InnerHtml = "The file attach have not content. Please choose another file.";
                    return false;
                }
                return true;
            }
            else
            {
                return true;
            }
        }


        /// <summary>
        /// Check file type 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private bool CheckFileType(string type)
        {
            for (int i = 0; i < Constants.arrFileType.Length; i++)
            {
                if (Constants.arrFileType[i].ToLower() == type.ToLower())
                {
                    return false;
                }
            }
            return true;
        }

        #endregion

        

       



    }
}
